package auth

import (
	"encoding/json"
	"log"
	"muziai-server/utils/req"
	"time"
)

var Access_Token string //access_token全局变量

// AccessTokenResponse 用于解析获取 Access Token 的响应
type AccessTokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

// 定义请求体结构体
type AccessTokenRequest struct {
	GrantType    string `json:"grant_type"`
	AppID        string `json:"appid"`
	Secret       string `json:"secret"`
	ForceRefresh bool   `json:"force_refresh"`
}

// GetAccessToken 使用通用 POST 请求获取 Access Token
func (w WxAuthService) GetAccessToken(appID, appSecret string, isForceRefresh bool) (string, int, error) {
	// 构建请求 URL
	url := "https://api.weixin.qq.com/cgi-bin/stable_token"

	// 构建请求体
	requestBody := AccessTokenRequest{
		GrantType:    "client_credential",
		AppID:        appID,
		Secret:       appSecret,
		ForceRefresh: isForceRefresh,
	}

	// 发送 POST 请求
	headers := map[string]string{}
	body, err := req.HttpPost(url, headers, requestBody)
	if err != nil {
		return "", 0, err
	}

	// 解析 JSON 响应
	var accessTokenResponse AccessTokenResponse
	err = json.Unmarshal(body, &accessTokenResponse)
	if err != nil {
		return "", 0, err
	}
	Access_Token = accessTokenResponse.AccessToken

	// 返回 Access Token 和 ExpiresIn
	return accessTokenResponse.AccessToken, accessTokenResponse.ExpiresIn, nil
}

// 定时获取微信 Access Token
func (w WxAuthService) StartAccessTokenScheduler(appID, appSecret string) {

	// 启动一个定时任务，每隔 2 小时执行一次获取 Access Token 的操作
	ticker := time.NewTicker(10 * time.Second)
	defer ticker.Stop()

	for range ticker.C {

		_, _, err := w.GetAccessToken(appID, appSecret, false)
		if err != nil {
			log.Println("Error getting Access Token:", err)
			continue
		}

	}
}
